package app.goods.info.utils;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.charts.XSSFCategoryAxis;

import app.goods.info.constants.GlobalCache;
import app.goods.info.services.domain.CataLogue;
import app.goods.info.services.domain.GoodsInfo;
import app.goods.info.services.domain.ShopInfo;
import app.goods.info.views.ColroTableCellRenderer;
import app.goods.info.views.MainFrame;
import app.goods.info.views.models.CatalogueGoodsNamesTableModle;

/**
 * 涉及界面操作的辅助类
 * 
 * @author 15050109
 *
 */
public class InterfaceUtils {
	public static void alignCenter(JFrame component) {
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		int Location_x = (int) (toolkit.getScreenSize().getWidth() - component.getWidth()) / 2;
		int Location_y = (int) (toolkit.getScreenSize().getHeight() - component.getHeight()) / 2;
		component.setLocation(Location_x, Location_y);
	}

	public static void alignCenter(JDialog component) {
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		int Location_x = (int) (toolkit.getScreenSize().getWidth() - component.getWidth()) / 2;
		int Location_y = (int) (toolkit.getScreenSize().getHeight() - component.getHeight()) / 2;
		component.setLocation(Location_x, Location_y);
	}

	public static void createMessageBox(String msg) {
		JOptionPane.showMessageDialog(null, msg);
	}

	public static JTable findJTableByName(Container container, String tableName) {
		if (container instanceof JTable) {
			JTable table = (JTable) container;
			if (tableName.equals(table.getName())) {
				return table;
			}
			return null;
		}

		for (Component component : container.getComponents()) {
			if (component instanceof Container) {
				JTable result = findJTableByName((Container) component, tableName);
				if (result != null) {
					return result;
				}
			}
		}

		return null;
	}

	public static <T extends Component> T getComponentByName(Container container, String componentName,
			Class<T> componentType) {
		if (container == null || componentName == null || componentType == null) {
			return null;
		}

		for (Component component : container.getComponents()) {
			if (componentType.isInstance(component) && component.getName() != null
					&& component.getName().equals(componentName)) {
				return componentType.cast(component);
			} else if (component instanceof Container) {
				Container container1 = (Container) component;
				T foundComponent = getComponentByName(container1, componentName, componentType);
				if (foundComponent != null) {
					return foundComponent;
				}
			}
		}
		return null;
	}

	/**
	 * 根据商品数量表，更新商品价格表，计算供应商总价并排序
	 */
	public static void cacaulateTotalPrice(JFrame frame) {
		Map<String, BigDecimal> allShopTotalPMapriceMap = new HashMap<>();
		List<CataLogue> cataLogues = GlobalCache.getInstance().getTargetCataLogues();
		// 供应商表
		JTable shopTable = InterfaceUtils.getComponentByName(frame, "table-shop-list", JTable.class);
		TableModel shopTableModel = shopTable.getModel();
		int shopRowCount = shopTableModel.getRowCount();
		for (CataLogue cataLogue : cataLogues) {
			// 商品名称表
			JTable namesTable = InterfaceUtils.getComponentByName(frame,
					"table-name-list-".concat(cataLogue.getCatalogueName()), JTable.class);
			TableModel namesTableModel = namesTable.getModel();
			// 商品表
			JTable goodsTable = InterfaceUtils.getComponentByName(frame,
					"table-goods-list-".concat(cataLogue.getCatalogueName()), JTable.class);
			TableModel goodsTableModel = goodsTable.getModel();

			// 遍历商品名称表和商品表，修改商品数量
			int namesRowCount = namesTableModel.getRowCount();
			int goodsRowCount = goodsTableModel.getRowCount();

			for (int i = 0; i < namesRowCount; i++) {
				String goodsName = (String) namesTableModel.getValueAt(i, 1);
				String goodsQuantiity = (String) namesTableModel.getValueAt(i, 2);
				goodsQuantiity = StringUtils.isEmpty(goodsQuantiity) ? "0" : goodsQuantiity;
				for (int j = 0; j < goodsRowCount; j++) {
					String goodsTableGoodsName = (String) goodsTableModel.getValueAt(j, 2);
					if (goodsName.equals(goodsTableGoodsName)) {
						goodsTableModel.setValueAt(goodsQuantiity, j, 5);
					}
				}
			}
			for (int i = 0; i < shopRowCount; i++) {
				String shopName = (String) shopTableModel.getValueAt(i, 0);
				BigDecimal totalPrice = new BigDecimal(0);
				for (int j = 0; j < goodsRowCount; j++) {
					String shopNameGoodsTable = (String) goodsTableModel.getValueAt(j, 1);
					String goodsPrice = (String) goodsTableModel.getValueAt(j, 4);
					String goodsQuantity = (String) goodsTableModel.getValueAt(j, 5);
					if (shopName.equals(shopNameGoodsTable)) {
						totalPrice = totalPrice.add(new BigDecimal(goodsPrice).multiply(new BigDecimal(goodsQuantity)));
					}
				}
				BigDecimal defaultValue = new BigDecimal(0);
				defaultValue.setScale(2);
				BigDecimal existTotalPrice = allShopTotalPMapriceMap.get(shopName) == null ? defaultValue
						: allShopTotalPMapriceMap.get(shopName);
				allShopTotalPMapriceMap.put(shopName, existTotalPrice.add(totalPrice));
			}

			for (int i = 0; i < shopRowCount; i++) {
				String shopName = (String) shopTableModel.getValueAt(i, 0);
				BigDecimal finalTotalPrice = allShopTotalPMapriceMap.get(shopName);
				shopTableModel.setValueAt(finalTotalPrice == null || "0".equals(finalTotalPrice.toString()) ? "0.00"
						: finalTotalPrice.toString(), i, 1);
			}

			TableRowSorter<TableModel> sorter = ((TableRowSorter<TableModel>) shopTable.getRowSorter());
			sorter.sort();
			goodsTable.repaint();
			shopTable.repaint();
		}

	}

	public static void resetAllCataLogueGoodsNumbers(JFrame frame) {

		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					List<CataLogue> cataLogues = GlobalCache.getInstance().getTargetCataLogues();
					for (CataLogue cataLogue : cataLogues) {
						// 商品名称表
						JTable namesTable = InterfaceUtils.getComponentByName(frame,
								"table-name-list-".concat(cataLogue.getCatalogueName()), JTable.class);
						TableModel namesTableModel = namesTable.getModel();
						int namesRowCount = namesTableModel.getRowCount();
						for (int i = 0; i < namesRowCount; i++) {
							namesTableModel.setValueAt("0", i, 2);
						}
						namesTable.repaint();
					}
					cacaulateTotalPrice(frame);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public static void refreshShopList(JFrame frame) {

		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					JTable shopTable = InterfaceUtils.getComponentByName(frame, "table-shop-list", JTable.class);
					DefaultTableModel shopTableModel = (DefaultTableModel) shopTable.getModel();
					int rowCount = shopTableModel.getRowCount();
					for (int i = rowCount - 1; i >= 0; i--) {
						shopTableModel.removeRow(i);
					}

					shopTable.revalidate();
					List<String> columnNames = new ArrayList<String>();
					columnNames.add("商家名称");
					columnNames.add("总价");
					List<ShopInfo> targetShops = GlobalCache.getInstance().getAllShopInfos().stream()
							.filter(shopInfo -> shopInfo.getStatus().equals("ON")).collect(Collectors.toList());

					for (int i = 0; i < targetShops.size(); i++) {
						ShopInfo shopInfo = targetShops.get(i);
						String[] dataRow = new String[2];
						dataRow[0] = shopInfo.getShopName();
						dataRow[1] = "0.00";
						shopTableModel.addRow(dataRow);
					}
					;

					shopTable.repaint();
					cacaulateTotalPrice(frame);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}